package map;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import model.ModelObject;
import entity.Avatar;
import entity.Entity;

public class GameWorld extends ModelObject {
	
	private static final GameWorld instance = new GameWorld();
	
	private GameMap currentMap;
	private GameMap previousMap;
	private ArrayList<GameMap> mapList;
	private Avatar avatar;
	//Maps the Entities to their model name for loading the AIs
	private Map<String, Entity> entityList = new HashMap<String, Entity>();
	
	private GameWorld() {
		super("game_world");
		
		this.currentMap = null;
		this.previousMap = null;
		this.mapList = new ArrayList<GameMap>();
		this.avatar = null;
	}
	
	public static GameWorld getInstance() {
		
		return instance;
	}
	
	public void addMap(GameMap map) {
		
		if(!mapList.contains(map)) {
			
			mapList.add(map);
			this.notifyObservers();
		}
	}
	
	void addEntity(Entity e) {
		entityList.put(e.getName(), e);
		this.notifyObservers();
	}
	
	public Entity getEntity(String entityModelName) {
		return entityList.get(entityModelName);
	}
	
	public GameMap getCurrentMap() {
		
		return this.currentMap;
	}
	
	public GameMap getPreviousMap() {
		
		return this.previousMap;
	}
	
	public GameMap getMap(String mapName) {
		
		GameMap mapToReturn = null;
		
		for(GameMap map : mapList) {
			
			if(map.getMapName().equals(mapName)) {
				
				mapToReturn = map;
				break;
			}
		}
		
		return mapToReturn;
	}
	
	public void setCurrentMap(GameMap map) {
		
		this.previousMap = this.currentMap;
		this.currentMap = map;
		map.initializeAI();
		this.notifyObservers();
	}
	
	public Avatar getAvatar() {
		
		return avatar;
	}
	
	public void setAvatar(Avatar avatar) {
		
		this.avatar = avatar;
	}
	
	public int getWidth() {
		if (currentMap != null) {
			return currentMap.getWidth();
		}
		return (0);
	}
	
	public int getHeight() {
		
		if (currentMap != null) {
			return currentMap.getHeight();
		}
		return (0);
	}
	
	public boolean isOccupied(Position position) {
		
		return currentMap.hasEntity(position);
	}
	
	public boolean isValidPosition(Position position) {
		
		return currentMap.isValidPosition(position);
	}
}
